package io.peng.dao;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import javax.sql.DataSource;

/**
 * Created by eric on 16/3/14.
 */

@Component
public class AccountDAO {

//    @Autowired
//    DataSource dataSource;

    JdbcTemplate jdbcTemplate;

    @Autowired
    public void AccountDao(DataSource dataSource) {
        this.jdbcTemplate = new JdbcTemplate(dataSource);
    }

    @Transactional
    public void transfer(int amount, String sender, String receiver) {
        String saveStatement = "update account set balance = balance + ? where name = ?";
        String withDrawStatement = "update account set balance = balance - ? where name = ?";
        System.out.println("transfer method");
//        JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
        jdbcTemplate.update(saveStatement, new Object[]{amount, receiver});
        jdbcTemplate.update(withDrawStatement, new Object[]{amount, sender});
    }

    @Transactional
    public void save(int amount, String name) {
//        JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
        jdbcTemplate.update("update account set balance = ? where name = ?", new Object[]{amount, name});
    }


}
